package com.jufanshare.tokenjwt.controller;

import com.jufanshare.tokenjwt.common.jwt.JwtRefreshSingle;
import com.jufanshare.tokenjwt.common.jwt.JwtUtils;
import com.jufanshare.tokenjwt.common.jwt.JwtValues;
import com.jufanshare.tokenjwt.common.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/backend")
public class LoginController {
    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private JwtValues jwtValues;

    /**
     * 登录
     * @param userName
     * @param password
     * @param response
     * @return
     */
    @PostMapping("/login")
    public Result login(String userName,String password, HttpServletResponse response) {

        if(StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)
                && "admin".equals(userName) && "123456".equals(password)){
            Map<String, Object> userInfo = new HashMap<>(2);
            userInfo.put("userName", userName);
            userInfo.put("expire", System.currentTimeMillis() + jwtValues.getTokenLogout() * 1000);
            String token = jwtUtils.generateToken(userInfo);
            response.setHeader("token",token);
            JwtRefreshSingle.getInstance().put(token,userInfo);
            return Result.ok(token);
        }
        return Result.error("账号或密码错误");
    }

    /**
     * 注销
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request,HttpServletResponse response){

        String token = request.getHeader(jwtUtils.getHeaderKey());

        Map<String, Object> tokenMap = JwtRefreshSingle.getInstance().get(token);
        if(null == tokenMap){
            return Result.error("token不存在");
        }
        JwtRefreshSingle.getInstance().remove(request.getHeader(jwtUtils.getHeaderKey()));
        response.setHeader("token","");
        return Result.ok("注销成功");
    }
}

